<template>
    <div class="add-pet-form">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="全名" prop="全名" :error="errors.全名">
                <el-input v-model="form.全名" placeholder="请输入宠物全名"></el-input>
            </el-form-item>

            <el-form-item label="别名" prop="别名" :error="errors.别名">
                <el-input v-model="form.别名" placeholder="请输入宠物别名"></el-input>
            </el-form-item>

            <el-form-item label="分类" prop="分类" :error="errors.分类">
                <el-select 
                    v-model="form.分类" 
                    placeholder="请选择分类" 
                    filterable 
                    allow-create
                    :before-create="handleBeforeCreate">
                    <el-option v-for="category in categories" :key="category" :label="category"
                        :value="category"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="体型" prop="体型">
                <el-input v-model="form.体型" placeholder="请输入体型"></el-input>
            </el-form-item>

            <el-form-item label="毛发" prop="毛发">
                <el-input v-model="form.毛发" placeholder="请输入毛发特征"></el-input>
            </el-form-item>

            <el-form-item label="智商" prop="智商">
                <el-input v-model="form.智商" placeholder="请输入智商"></el-input>
            </el-form-item>

            <el-form-item label="寿命" prop="寿命">
                <el-input v-model="form.寿命" placeholder="请输入寿命"></el-input>
            </el-form-item>

            <el-form-item label="饲养" prop="饲养">
                <el-input v-model="form.饲养" type="textarea" rows="3" placeholder="请输入饲养信息"></el-input>
            </el-form-item>

            <el-form-item label="功能" prop="功能">
                <el-input v-model="form.功能" placeholder="请输入功能"></el-input>
            </el-form-item>

            <el-form-item label="原产地" prop="原产地">
                <el-input v-model="form.原产地" placeholder="请输入原产地"></el-input>
            </el-form-item>

            <el-form-item label="价格" prop="价格">
                <el-input v-model="form.价格" placeholder="请输入价格"></el-input>
            </el-form-item>

            <!-- <el-form-item label="图片路径" prop="imgPath">
                <el-input v-model="form.imgPath" placeholder="请输入图片路径"></el-input>
            </el-form-item> -->

            <el-form-item label="简介" prop="简介">
                <el-input v-model="form.简介" type="textarea" rows="4" placeholder="请输入宠物简介"></el-input>
            </el-form-item>

            <el-form-item label="图片" prop="imgPath" :error="errors.imgPath">
                <el-upload
                    class="avatar-uploader"
                    :action="`${baseURL}/image/upload`"
                    :show-file-list="false"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :before-upload="beforeUpload">
                    <img v-if="imageUrl" :src="getImageUrl(form.imgPath)" class="avatar">
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <div class="image-tip">支持 jpg、jpeg、png 格式，大小不超过 500KB</div>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm">确认</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { addPet, getPetCategories } from '@/api/admin';
import { getimage } from '@/api/image';
import request from "@/util/http";

const emit = defineEmits(['cancel', 'success']);
const baseURL = request.defaults.baseURL;

const formRef = ref(null);
const categories = ref([]);
const imageUrl = ref('');

const form = ref({
    全名: '',
    别名: '',
    分类: '',
    体型: '',
    毛发: '',
    智商: '',
    寿命: '',
    饲养: '',
    功能: '',
    原产地: '',
    价格: '',
    imgPath: '',
    简介: ''
});

// 添加错误提示对象
const errors = reactive({
    全名: '',
    别名: '',
    分类: '',
    体型: '',
    毛发: '',
    智商: '',
    寿命: '',
    饲养: '',
    功能: '',
    原产地: '',
    价格: '',
    imgPath: '',
    简介: ''
});

// 表单验证
const validate = () => {
    errors.全名 = form.value.全名 ? '' : '宠物全名不能为空';
    errors.分类 = form.value.分类 ? '' : '请选择宠物分类';
    errors.简介 = form.value.简介 ? '' : '宠物简介不能为空';
    errors.imgPath = form.value.imgPath ? '' : '请上传宠物图片';
    
    return !Object.values(errors).some(error => error);
};

// 重置表单
const resetForm = () => {
    if (!formRef.value) return;
    formRef.value.resetFields();
    imageUrl.value = '';
    Object.keys(errors).forEach(key => errors[key] = '');
};

// 分类创建前的验证
const handleBeforeCreate = (value) => {
    if (categories.value.includes(value)) {
        ElMessage.warning('该分类已存在');
        return false;
    }
    if (value.length > 20) {
        ElMessage.warning('分类名称不能超过20个字符');
        return false;
    }
    categories.value.push(value);
    return true;
};

const submitForm = async () => {
    if (!validate()) {
        ElMessage.error('请检查表单填写');
        return;
    }

    try {
        // 构建提交数据，确保所有必填字段都有值
        const submitData = {
            全名: form.value.全名.trim(),  // 去除空格
            别名: form.value.别名 || '',
            分类: form.value.分类 || '',
            体型: form.value.体型 || '',
            毛发: form.value.毛发 || '',
            智商: form.value.智商 || '',
            寿命: form.value.寿命 || '',
            饲养: form.value.饲养 || '',
            功能: form.value.功能 || '',
            原产地: form.value.原产地 || '',
            价格: form.value.价格 || '',
            imgPath: form.value.imgPath || '',
            简介: form.value.简介.trim()  // 去除空格
        };

        // 再次验证必填字段
        if (!submitData.全名 || !submitData.简介) {
            ElMessage.error('全名和简介不能为空');
            return;
        }

        console.log('提交的数据：', submitData); // 添加日志

        const { data } = await addPet(submitData);
        
        if (data.code === 200) {
            ElMessage.success('添加成功');
            resetForm();
            emit('success');
        } else {
            // 显示后端返回的具体错误信息
            if (data.errors) {
                Object.entries(data.errors).forEach(([field, message]) => {
                    errors[field] = message;
                    ElMessage.error(`${field}: ${message}`);
                });
            } else {
                ElMessage.error(data.message || '添加失败');
            }
        }
    } catch (error) {
        console.error('提交错误：', error.response?.data); // 添加错误日志
        if (error.response?.data) {
            const responseData = error.response.data;
            if (responseData.errors) {
                Object.entries(responseData.errors).forEach(([field, message]) => {
                    errors[field] = message;
                    ElMessage.error(`${field}: ${message}`);
                });
            } else {
                ElMessage.error(responseData.message || '提交失败');
            }
        } else {
            ElMessage.error('网络错误，请稍后重试');
        }
    }
};

const rules = {
    全名: [{ required: true, message: '请输入宠物全名', trigger: 'blur' }],
    分类: [{ required: true, message: '请选择宠物分类', trigger: 'change' }],
    简介: [{ required: true, message: '请输入宠物简介', trigger: 'blur' }]
};

const fetchCategories = async () => {
    try {
        const { data } = await getPetCategories();
        if (data.code === 200) {
            categories.value = data.data;
        }
    } catch (error) {
        ElMessage.error('获取分类失败：' + error.message);
    }
};

// 图片上传相关方法
const handleUploadSuccess = (res) => {
    if (res.code === 200 || res.url) {
        form.value.imgPath = res.url;
        imageUrl.value = getImageUrl(res.url);
        ElMessage.success('图片上传成功');
    } else {
        ElMessage.error(res.error || '上传失败');
    }
};

const handleUploadError = (error) => {
    ElMessage.error('图片上传失败：' + error.message);
};

const beforeUpload = (file) => {
    const isAllowed = ['image/jpeg', 'image/jpg', 'image/png'].includes(file.type);
    const isLt500K = file.size / 1024 < 500;

    if (!isAllowed) {
        ElMessage.error('只能上传 JPG/PNG 格式的图片！');
        return false;
    }
    if (!isLt500K) {
        ElMessage.error('图片大小不能超过 500KB！');
        return false;
    }
    return true;
};

const getImageUrl = (path) => {
    if (!path) return '';
    return getimage(path);
};

onMounted(() => {
    fetchCategories();
});
</script>

<style scoped>
.add-pet-form {
    padding: 20px;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
}

.avatar-uploader:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.image-tip {
    font-size: 12px;
    color: #666;
    margin-top: 5px;
}
</style>